<template>
    <div>
      <!-- 数据表格 -->
      <el-scrollbar class="com_table">
        <el-table :data="formData" style="width: 100%">
          <el-table-column prop="username" label="用户名" />
          <el-table-column width="250" label="编辑/删除">
            <template #default="scope">
              <el-button @click="edit(scope.row.uid)" size="small" type="warning">初始用户密码</el-button>
              <el-button @click="del(scope.row.uid)" size="small" type="danger">删除用户</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
      <!-- 分页栏 -->
      <div class="pagination">
        <el-pagination background :default-page-size="listCount" layout="prev, pager, next" :total="totalCount"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </template>
  
  <script setup>
  import { watch, inject, ref } from 'vue'
  import { useRouter } from 'vue-router'
  const router = useRouter()
  const $root = inject('$root')
  /* 页面表格数据 */
  let formData = ref([])
  const $axios = inject('$axios')
  /* 定义总数据条数 */
  let totalCount = ref(0)
  /* 定义每页显示的数据条数 */
  let listCount = 10
  /* 获取页面数据 */
  const getPageData = (pageNO = 1) => {
    $axios.get($root + `/user/list/?page=${pageNO}&page_size=${listCount}`)
      .then(r => {
        console.log(r)
        if (r.data.code == 200) {
          formData.value = r.data.data.data
          totalCount.value = r.data.data.total_count
        }
      })
  }
  
  /* 分页栏功能 */
  const handleCurrentChange = (e) => {
    /* e为当前页 */
    getPageData(e)
  }
  
  /* 删除数据 */
  const del = (id) => {
    $axios.post($root + `/user/delete/${id}/`)
      .then(r => {
        if (r.data.code == 200) {
          getPageData()
          ElMessage({
            message: '删除数据成功',
            type: 'success',
          })
        }
        else {
          ElMessage.error('删除数据失败')
        }
      })
  }
  
  /* 编辑数据 */
  const edit = (id) => {
    $axios.post($root + `/user/updatePassword/${id}/`, {
      "new_password": "123456"
    })
      .then(r => {
        if (r.data.code = 200) {
          ElMessage({
            message: '更新数据成功',
            type: 'success',
          })
        }
        else {
          ElMessage.error('更新数据失败')
        }
      })
  }
  
  
  watch(() => router.currentRoute.value.name, (name) => {
    if (name == "users") {
      getPageData()
    }
  }, { immediate: true, deep: true })
  
  </script>
  
  <style scoped>
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 15px;
  }
  </style>